require(["config"],function(){
	//引入依赖模块
	require(["jquery","template","header", "zoom", "fly", "cookie"],function($,template){
		function Detail(){
			this.render();
		}
		
		Detail.prototype = {
			constructor :Detail,
			
			render : function(){
				$.ajax("http://rap2api.taobao.org/app/mock/94964/example/1539740532668")
					.done($.proxy(this.handleData, this));	
			},
			
			handleData : function(data){
				var data = {list :data.res_body.list};
				
				console.log(data);
				
				var html = template("detail_template",data);
				$(".detail-content").prepend(html);
				this.zoom();
				this.addListener();
				
			},
			zoom: function() {
				$(".middle-zoom").elevateZoom({
					gallery:'gal1', 
					cursor: 'pointer', 
					galleryActiveClass: 'active'
				});
			},
			addListener : function(){
				$(".add-cart-button").click(this.addtoCarHandler);
			},
			addtoCarHandler : function(){
				var currentProduct = {
					id:$(".id").text(),
					name : $(".cake-name").text(),
					img : $("#gal1 li:first img").attr("src"),
					price : $(".price").text(),
					weightsize : $(".choose-size abbr").text(),
					amount : $(".amount").text(),
					series : $(".sitmap-one").text()
				};
				
				console.log(currentProduct);
				$.cookie.json = true; // 配置自动在JS值与JSON文本之间相互转换
				var products = $.cookie("cart") || [];
				// 判断是否已有选购
				var has = products.some(function(prod) {
					if (prod.id == currentProduct.id) { // 已有选购商品
						prod.amount++; // 数量自增
						return true;
					}
					return false;
				});
				if (!has) // 未选购
					products.push(currentProduct);
				console.log(products);
				// 保存购物车：存回cookie
				// 数据结构：[{id,title,img,price,amout},{id,title,img,price,amout},{id,title,img,price,amout}]
				$.cookie("cart", products, {expires: 10, path:"/"});
				//抛物线
				var end = $(".car").offset();
				end.top -= $(window).scrollTop();
				var start = {top: event.pageY - $(window).scrollTop(), left: event.pageX};
				var flyer = $("#gal1 li:first img").clone();
				
				flyer.attr("width","50px");
				flyer.attr("height","50px");
				
				flyer.fly({
					start,
					end,
					onEnd:function(){
						this.destroy();
					}
				});
			}
			
		}
		new Detail();
	});
});
